package com.mapaower.project.service.impl;

import com.mapaower.project.dao.ProjectApplicationRepository;
import com.mapaower.project.entity.ProjectApplication;
import com.mapaower.project.service.ProjectApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 项目报名服务实现类
 * 实现项目报名相关的业务逻辑
 */
@Service
public class ProjectApplicationServiceImpl implements ProjectApplicationService {

    @Autowired
    private ProjectApplicationRepository applicationRepository;

    @Override
    public ProjectApplication createApplication(ProjectApplication application) {
        // 设置默认状态为待审核
        application.setStatus(ProjectApplication.ApplicationStatus.PENDING);
        return applicationRepository.save(application);
    }

    @Override
    public ProjectApplication updateApplication(ProjectApplication application) {
        return applicationRepository.save(application);
    }

    @Override
    public Optional<ProjectApplication> getApplicationById(Long id) {
        return applicationRepository.findById(id);
    }

    @Override
    public List<ProjectApplication> getApplicationsByProjectId(Long projectId) {
        return applicationRepository.findByProjectId(projectId);
    }

    @Override
    public List<ProjectApplication> getApplicationsByDeveloperId(Long developerId) {
        return applicationRepository.findByDeveloperId(developerId);
    }

    @Override
    public boolean hasApplied(Long projectId, Long developerId) {
        ProjectApplication application = applicationRepository.findByProjectIdAndDeveloperId(projectId, developerId);
        return application != null;
    }

    @Override
    public ProjectApplication updateApplicationStatus(Long id, ProjectApplication.ApplicationStatus status) {
        Optional<ProjectApplication> optionalApplication = applicationRepository.findById(id);
        if (optionalApplication.isPresent()) {
            ProjectApplication application = optionalApplication.get();
            application.setStatus(status);
            return applicationRepository.save(application);
        }
        throw new RuntimeException("Application not found with id: " + id);
    }

    @Override
    public ProjectApplication withdrawApplication(Long id) {
        return updateApplicationStatus(id, ProjectApplication.ApplicationStatus.WITHDRAWN);
    }

    @Override
    public void deleteApplication(Long id) {
        applicationRepository.deleteById(id);
    }
}